import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import 'element-plus/theme-chalk/el-message.css'
import admin_service from "../../service/admin_service";

export default function Classification() {
    onMounted(() => {
        admin_service.getSorts().then(r => {
            let data = r.data
            for (let i = 0; i < data['msg'].length; i++) {
                let dataList = {}
                dataList.id = data['msg'][i]['ID']
                dataList.urlName = data['msg'][i]['UrlName']
                dataList.name = data['msg'][i]['Name']
                draggableList.value.push(dataList)
            }
        })
    })
    let menuName = ref('')
    let menuUrlName = ref('')
    let draggableList = ref([])
    const saveMenuBtn = () => {
        let dataList = []
        for (let i = 0; i < draggableList.value.length; i++) {
            let tmpObj = {}
            tmpObj.name = draggableList.value[i].name
            tmpObj.index = i
            tmpObj.urlName = draggableList.value[i].name
            dataList.push(tmpObj)
        }
        admin_service.sortMenu({data: dataList}).then(r => {
            let data = r.data
            if (data.code === 200) {
                ElMessage.success("保存成功！")
            } else {
                ElMessage.error("保存失败！")
            }
        })
    }
    const addSortBtn = () => {
        if (menuUrlName.value !== '' && menuName.value !== '') {
            let obj = {
                url_name: menuUrlName.value,
                name: menuName.value
            }
            admin_service.addSort(obj).then(r => {
                if (r.data.code === 200) {
                    ElMessage.success("添加成功")
                    obj.urlName = obj.url_name
                    draggableList.value.push(obj)
                    menuName.value = ''
                    menuUrlName.value = ''
                } else {
                    ElMessage.error("添加失败")
                }
            })

        } else {
            ElMessage.error("请填写菜单名字与索引内容")
        }

    }
    const deleteMenuBtn = (e) => {
        admin_service.deleteSort({sort_name: e}).then(r => {
            let data = r.data
            if (data.code === 200) {
                draggableList.value = []
                for (let i = 0; i < data.msg.length; i++) {
                    let dataList = {}
                    dataList.id = data.msg[i].UrlName
                    dataList.name = data.msg[i].Name
                    draggableList.value.push(dataList)
                }
                ElMessage.success("删除成功")
            } else {
                ElMessage.error("删除失败")
            }
        })
    }
    return {
        menuName,
        draggableList,
        saveMenuBtn,
        addSortBtn,
        menuUrlName,
        deleteMenuBtn
    }
}